import BackPage from '@/components/BackPage';
import SelectOne from '@/components/SelectOne';
import { addBan } from '@/services/banned';
import { getAllUser } from '@/services/user';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import moment from 'moment';
import { useCallback, useEffect, useRef, useState } from 'react';
import styles from './index.less';

const Users: React.FC = () => {
  const [form] = Form.useForm();
  const { TextArea } = Input;
  const actionRef = useRef<ActionType>();
  const [actionModal, setActionModal] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);
  const [selectList, setSelectList] = useState<any[]>([]);
  const [willBan, setWillBan] = useState<string>('');
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  // 初始值
  const getInitValues = () => {
    return {
      disable: '1',
    };
  };
  const confirmSubmit = async (values: any) => {
    try {
      await addBan(values).then(() => {
        message.success('禁言成功！');
      });
      setActionModal(false);
      form.setFieldsValue({ disable: '1', reason: '' });
    } catch (error) {
      console.log(error);
    }
  };

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const onFinish = async () => {
    let values = await form.validateFields();
    values.userid = willBan;

    Modal.confirm({
      title: '禁言',
      centered: true,
      content: '是否禁言该用户？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => confirmSubmit(values),
    });
  };

  const columns: ProColumns<any>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '买家编号',
      dataIndex: 'id',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      ellipsis: true,
    },
    {
      title: '注册时间',
      key: 'timeadd',
      render: (text, record) => [
        <div key={record.id}>{`${moment(Number(record.timeadd)).format(
          'YYYY-MM-DD HH:mm:ss',
        )}`}</div>,
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (text, record) => [
        <div
          key={record.id}
          className={styles.delete}
          onClick={() => {
            setActionModal(true);
            setWillBan(record.id);
          }}
          style={{ border: `1px solid ${colorThem}`, color: colorThem }}
        >
          禁言
        </div>,
      ],
    },
  ];

  const getList = useCallback(async () => {
    try {
      const res = await getAllUser({ role: '1', pageIndex: currentPage });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage]);

  useEffect(() => {
    getList();
  }, [getList]);

  return (
    <BackPage thisRoute={'/users'} lastRoute={'买家管理'}>
      <div className={styles.container}>
        <SelectOne
          searchText={'买家编号'}
          fromWhere={'user'}
          selected={(value) => {
            setSelectList(value);
          }}
          clear={() => {
            setSelectList([]);
          }}
        />
        <ProTable<any>
          columns={columns}
          actionRef={actionRef}
          cardBordered={false}
          dataSource={selectList.length !== 0 ? selectList : list}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={false}
          options={false}
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
          dateFormatter="string"
          headerTitle=""
        />
        <Modal
          visible={actionModal}
          onCancel={() => {
            setActionModal(false);
            form.setFieldsValue({ disable: '1', reason: '' });
          }}
          footer={[
            <>
              <Button
                onClick={() => {
                  setActionModal(false);
                  form.setFieldsValue({ disable: '1', reason: '' });
                }}
                className={styles.btnCancel}
              >
                取消
              </Button>
              <Button
                className={styles.btnSeal}
                style={{ background: `${colorThem}`, width: 120, color: '#fff' }}
                htmlType="submit"
                type="primary"
                onClick={onFinish}
              >
                确定
              </Button>
            </>,
          ]}
        >
          <div className={styles.actionContent}>
            <Form
              className={styles?.formStyle}
              onFinish={onFinish}
              form={form}
              initialValues={getInitValues()}
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 28 }}
            >
              <Form.Item
                label="禁言类型"
                name="disable"
                rules={[
                  {
                    required: true,
                    message: (
                      <div>
                        <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                        请选择禁言类型
                      </div>
                    ),
                  },
                ]}
              >
                <Select
                  defaultValue="1"
                  style={{ width: 200, marginTop: 10 }}
                  options={[
                    { key: '1', value: '1', label: '仅禁止通话' },
                    { key: '1', value: '2', label: '仅禁止评论' },
                    { key: '1', value: '3', label: '禁止通话且禁止评论' },
                  ]}
                />
              </Form.Item>
              <Form.Item
                label="禁言原因"
                name="reason"
                validateTrigger="onBlur"
                rules={[
                  {
                    required: true,
                    message: (
                      <div>
                        <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                        请输入禁言原因
                      </div>
                    ),
                  },
                  {
                    pattern: new RegExp(/^[\u4e00-\u9fa5_a-zA-Z0-9]{4,200}$/),
                    message: (
                      <div>
                        <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                        请输入4-200个字符（包括中文，英文字母和数字及下划线）
                      </div>
                    ),
                  },
                ]}
              >
                <TextArea
                  maxLength={200}
                  placeholder={'请输入禁言原因'}
                  autoSize={{ minRows: 6, maxRows: 6 }}
                  showCount
                />
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </div>
    </BackPage>
  );
};
export default Users;
